import React from 'react';
import { InputNumber } from 'antd';
import { isFunction } from '../../../utils/is-object';

export default function createInput(options = {}) {
  const {
    property,
    data = {},
    size = 'small',
    onChange,
    onEnter,
    getter = (data, property) => data[property],
    getValue = value => value
  } = options;
  const onChangeHandler = value => {
    if (isFunction(getValue)) {
      value = getValue(value);
    }
    if (isFunction(onChange)) {
      onChange(value, property);
    }
  };
  const onKeyUp = event => {
    let { value } = event.target;
    const { key } = event;
    if (isFunction(getValue)) {
      value = getValue(value);
    }
    switch (key) {
      case 'Enter':
        if (isFunction(onEnter)) {
          onEnter(value, property);
        }
        break;
      default:
        break;
    }
  };
  const onBlur = event => {
    let { value } = event.target;
    if (isFunction(getValue)) {
      value = getValue(value);
    }
    if (isFunction(onEnter)) {
      onEnter(value, property);
    }
  };
  const value = getter(data, property);
  return (
    <InputNumber
      value={value}
      size={size}
      onKeyUp={onKeyUp}
      onChange={onChangeHandler}
      onBlur={onBlur}
      min={0}
    />
  );
}
